package com.example.myfirstapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.myfirstapplication.utils.BaseActivity
import com.example.myfirstapplication.utils.LOG
import com.example.myfirstapplication.utils.Tag
import kotlinx.android.synthetic.main.activity_network.*
import okhttp3.*
import okio.IOException
import java.io.BufferedReader
import java.io.DataOutputStream
import java.io.InputStreamReader
import java.lang.StringBuilder
import java.net.HttpURLConnection
import java.net.URL
import kotlin.concurrent.thread

class NetworkActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_network)
        btnHttpConnection.setOnClickListener {
            postDataWithHttpURLConnection()
        }
    }

    private fun postDataWithHttpURLConnection() {
        thread {
            var connection: HttpURLConnection? = null
            try {
                var response = StringBuilder()
                val url = URL("https://api.neiyu.com/test")
                connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "POST"
                val output = DataOutputStream(connection?.outputStream)
                output.writeBytes("name=neiyu&test=444")
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                val input = connection.inputStream
                val reader = BufferedReader(InputStreamReader(input))
                reader.use {
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                showResponse(response.toString())
                showContents.text = response.toString()
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                connection?.disconnect()
            }
        }
    }

    private fun sendRequestWithHttpURLConnection() {
        thread {
            var connection: HttpURLConnection? = null
            try {
                var response = StringBuilder()
                val url = URL("https://widget.cifuwu.com/weather")
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout = 8000
                connection.readTimeout = 8000
                val input = connection.inputStream
                val reader = BufferedReader(InputStreamReader(input))
                reader.use {
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                showResponse(response.toString())
                showContents.text = response.toString()
            } catch (e: Exception) {
                e.printStackTrace()
            } finally {
                connection?.disconnect()
            }
        }
    }

    private fun showResponse(response: String) {
        runOnUiThread {
            showContents.text = response
        }
    }

    //同步获取
    private fun sendRequestWithOkHttp() {
        thread {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("https://widget.cifuwu.com/weather")
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData != null) {
                    LOG.i(responseData.toString())
                    showResponse(responseData)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    //异步获取
    private fun sendRequestWithOkHttpAsync() {
        try {
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("https://widget.cifuwu.com/weather")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    TODO("Not yet implemented")
                }

                override fun onResponse(call: Call, response: Response) {
                    val responseData = response.body?.string()
                    if (responseData != null) {
                        Log.d("MainActivity", responseData.toString())
                    }
                }

            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    //同步提交
    private fun sendRequestWithOkHttpPost() {
        thread {
            try {
                //创建一个RequestBody(参数1：数据类型 参数2传递的json串)
                val params = mapOf<String, String>(
                    "name" to "jcifox", "gender" to "male"
                )
                val body = buildParams(params)
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("http://api.nieyu.com/test")
                    .post(body)
                    .build()
                val response = client.newCall(request).execute()
                val responseData = response.body?.string()
                if (responseData != null) {
                    Log.i(Tag, responseData.toString())
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    fun buildParams(param: Map<String, String>?): RequestBody {
        var params: Map<String, String>? = param
        if (params == null) {
            params = HashMap<String, String>()
        }
        val builder = FormBody.Builder()
        for (entry in params.entries) {
            val key = entry.key
            var value: String? = entry.value
            if (value == null) {
                value = ""
            }
            builder.add(key, value)
        }
        return builder.build()
    }

    //异步提交
    private fun sendRequestWithOkHttpAsyncPost() {
        try {
            val params = mapOf<String, String>(
                "name" to "Nelson", "gender" to "male"
            )
            val body = buildParams(params)
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://api.nieyu.com/test")
                .post(body)
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    TODO("Not yet implemented")
                }

                override fun onResponse(call: Call, response: Response) {
                    val responseData = response.body?.string()
                    if (responseData != null) {
                        Log.d("MainActivity", responseData.toString())
                    }
                }
            })
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}

